package com.controller;

import com.bean.PaginationSupport;
import com.bean.Post;
import com.bean.User;
import com.db.PostRepository;
import com.db.UserRepository;
import com.web.CookieTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

@Controller
@RequestMapping("/")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PostRepository postRepository;

    @RequestMapping(method = GET)
    public String showUserHome(Model model){
        return "index";
    }

    @RequestMapping(value="/login", method = GET)
    public String showUserLogin(Model model,@CookieValue(value = "username", defaultValue= "") String username,
                                @CookieValue(value = "password", defaultValue= "") String password){

        return "login";
    }

    @RequestMapping(value = "/login",method = POST)
    public String processUserLogin(@RequestParam(value = "username",defaultValue = "") String username,
                                   @RequestParam(value = "password",defaultValue = "") String password, HttpSession session,
                                   HttpServletResponse response) throws UnsupportedEncodingException {
        boolean usernameisnull = false;
        boolean passwordisnull = false;
        String errormessage = "错误：";

        username = new String(username.getBytes("ISO-8859-1"),"utf-8");
        password = new String(password.getBytes("ISO-8859-1"),"utf-8");

        if(username.equals("") || username == null){
            usernameisnull = true;
            errormessage += " 用户名为空 ";
        }
        if(password.equals("") || password == null){
            passwordisnull = true;
            errormessage += " 密码为空 ";
        }
        if((!usernameisnull) && (!passwordisnull)){

            User user = userRepository.findByUserName(username, password);
            System.out.println(username + "========" + password);
            if(user != null){
                session.setAttribute("user", user);
                /*Cookie cookiename=new Cookie("username",username);
                response.addCookie(cookiename);
                Cookie cookiepassword=new Cookie("username",username);
                response.addCookie(cookiename);*/
                CookieTool.addCookie(response,"username",username,10*60);
                CookieTool.addCookie(response,"password",password,10*60);
                return "redirect:/userHomePage";
            }else{
                errormessage += " 用户名或密码错误 ";
                session.setAttribute("userLoginErrorMessage", errormessage);
                return "loginError";
            }
        }else{
            session.setAttribute("userLoginErrorMessage", errormessage);
            return "loginError";
        }
    }

    @RequestMapping(value ="/userHomePage",method = GET)
    public String showUserHomePage(@RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
                                   @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,Model model){

        model.addAttribute("paginationSupport",postRepository.findAllPostPage(pageNo, pageSize));
        return "userHomePage";
    }

    @RequestMapping(value = "/register", method = GET)
    public String showUserRegister(Model model){
        return "userRegister";
    }


    @RequestMapping(value = "/register", method = POST)
    public String processUserRegister(@RequestParam(value = "username", defaultValue = "") String username,
                                      @RequestParam(value = "password", defaultValue = "") String password,
                                      HttpSession session, HttpServletRequest Request, HttpServletResponse Response) throws UnsupportedEncodingException {
        boolean usernameisnull = false;
        boolean passwordisnull = false;
        String errormessage = "错误：";

        username = new String(username.getBytes("ISO-8859-1"),"utf-8");
        password = new String(password.getBytes("ISO-8859-1"),"utf-8");

        if(username.equals("") || username == null){
            usernameisnull = true;
            errormessage += " 用户名为空 ";
        }
        if(password.equals("") || password == null){
            passwordisnull = true;
            errormessage += " 密码为空 ";
        }
        if((!usernameisnull) && (!passwordisnull)){
            User newUser = userRepository.findByUserName(username);
            if(newUser == null){

                int userNumber = userRepository.maxuserid() + 1;
                User user = new User(userNumber,username, password, false);
                userRepository.save(user);
                return "redirect:/login";
            }else{
                errormessage += " 用户名已存在 ";
                session.setAttribute("userRegisterErrorMessage", errormessage);
                return "userRegisterError";
            }
        }else{
            session.setAttribute("userRegisterErrorMessage", errormessage);
            return "userRegisterError";
        }

    }

    @RequestMapping(value = "/logout", method = GET)
    public String processUserLogout(HttpSession session,HttpServletResponse response){
        CookieTool.addCookie(response,"username",null,0);//注销时清除cookie
        CookieTool.addCookie(response,"password",null,0);
        session.removeAttribute("user");
        session.invalidate();

        return "redirect:/userHomePage";
    }




}
